package com.wnxy.portal.rabbit.listener;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.wnxy.portal.common.constant.RedisConstant;
import com.wnxy.portal.rabbit.config.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ClearCartListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = "clearCartQueue")
    public void clearCartHandler(
            String content,Message message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        log.debug("清空购物车Listener，消息内容：{}",content);
        try {
            // json转换为对象
            Map<String,Object> map = JSONUtil.toBean(content,Map.class);
            List<Integer> bookIds = (List<Integer>) map.get("bookIds");
            Integer userId = (Integer) map.get("userId");
            if (userId != null && bookIds != null && bookIds.size() > 0) {
                // 删除购物车中购物项
                bookIds.stream().forEach(bookId -> {
                    String key = RedisConstant.USER_CART_PREFIX + userId;
                    redisTemplate.opsForHash().delete(key,bookId.toString());
                });
            }
            // 手动应答
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            e.printStackTrace();
            // 获取重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (redelivered) {
                // 已经重投过，拒绝
                channel.basicReject(deliveryTag,false);
            } else {
                // 重投
                channel.basicNack(deliveryTag, false, true);
            }
        }
    }
}
